package api

import (
	"jgt-sdk/asapi"
	"net/http"

	"github.com/gin-gonic/gin"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/api/infos"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/api/interaction"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/api/api/report"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/ginsrv/oplog"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/oplogd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd/ginhook"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd/repo/mgorepo"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/debug"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/log"
)

// Init 初始化管理api
func Init(s ginsrv.Server) {
	s.RegStartHook(func(e *gin.Engine) {
		route := e.Group("/api")
		route.Use(ginhook.DDDContext(func(c *gin.Context) string {
			uid := c.Request.Header.Get("X-Jgt-Userid")
			oplog.WrapModules(c, func(ol *oplogd.OpLogEntity) {
				ol.Module = "cmsapi"
				ol.UID = uid
			})
			if debug.IsDev() {
				if uid == "" {
					uid = "000000"
				}
			}
			log.WrapUIDForContext(c, uid)
			return uid
		}))
		route.Use(mgorepo.MgoContext(s.Domain()))
		cored := s.Domain().(core.CmsDomain)

		route.Use(oplog.Oplog(cored.OpLog()))
		if !debug.IsDev() {
			route.Use(func(c *gin.Context) {
				log.FromContext(c).Debugf("协议:%v 请求头:%v", c.Request.Proto, c.Request.Header)
				_, err := asapi.GetAPI().VerifyToken(c.Request.Header.Get("X-JGT-TOKEN"))
				if err != nil {

					c.JSON(http.StatusUnauthorized, gin.H{"status": 1, "error": "未认证不能操作"})
					c.Abort()
				}
			})
		}

		v1 := route.Group("v1")
		infos.Init(v1, cored)
		// 信息相关
		interaction.Init(v1.Group("ints"), cored)

		report.Init(v1.Group("report"), cored)
	})
}
